package com.h3bpm.kumhosunny.complaints.controller;

import OThinker.Common.DateTimeUtil;
import OThinker.Common.DotNetToJavaStringHelper;
import OThinker.Common.Organization.Models.Unit;
import OThinker.Common.Organization.Models.User;
import OThinker.Common.Organization.enums.UnitType;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Entity.Instance.InstanceContext;
import OThinker.H3.Entity.WorkflowTemplate.Activity.Activity;
import OThinker.H3.Entity.WorkflowTemplate.Activity.Client.ClientActivityBase;
import OThinker.H3.Entity.WorkflowTemplate.WorkflowDocument.PublishedWorkflowTemplate;
import OThinker.H3.Portal.webservices.BPMService;
import OThinker.H3.Portal.webservices.Entity.BPMServiceResult;
import OThinker.H3.Portal.webservices.Entity.DataItemParam;
import OThinker.H3.Portal.webservices.impl.BPMServiceImpl;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.h3bpm.base.res.ResBody;
import com.h3bpm.kumhosunny.common.utils.SqlUtil;
import data.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.*;

/***
 * 客户投诉流程
 */
@Controller
@RequestMapping(value = "/Portal/CustomerComplaintsController")
public class CustomerComplaintsController extends ControllerBase {

    private static final Logger logger = LoggerFactory.getLogger(CustomerComplaintsController.class);

    private BPMService bpmService = new BPMServiceImpl();

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String getFunctionCode() {
        return null;
    }

    /***
     * 根据项目编号查询客诉单流程 instanceId
     * @param projectId
     * @return
     */
    public String findComplaintsForm(String projectId) {
        String instanceId = "";
        String querySql = String.format("SELECT RunningInstanceId from i_containmentactions WHERE Number02='%s' LIMIT 1", projectId);
        try {
            DataTable dataTable = SqlUtil.doQuery(querySql);
            if (dataTable.getRows().size() > 0) {
                instanceId = dataTable.getRows().get(0).getString(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return instanceId;
    }

    /***
     * 生成项目唯一ID
     * @return
     */
    //http://localhost:8081/Portal/CustomerComplaintsController/getNewProjectNumber
    @RequestMapping(value = "/getNewProjectNumber")
    @ResponseBody
    public ResBody getNewProjectNumber() {
        Date nowDate = new Date();
        String projectNumber = "";
        String yearStr=String.valueOf(DateTimeUtil.getYear(nowDate));
        String dateStr = yearStr.substring(2) + "" + String.format("%02d", DateTimeUtil.getMonth());
        String querySql = " SELECT Number02 from i_ContainmentActions WHERE Number02 LIKE '" + dateStr + "%' ORDER BY Number02 DESC LIMIT 1 ";

        try {
            DataTable dataTable = SqlUtil.doQuery(querySql);

            if (dataTable.getRows() != null && dataTable.getRows().size() > 0) {
                String nowNumber = dataTable.getRows().get(0).getString(0);
                int num = Integer.parseInt(nowNumber.split(dateStr)[1]);
                projectNumber = dateStr + String.format("%03d", num + 1);
            } else {
                projectNumber = dateStr + "001";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("[客户投诉流程]新编号:" + projectNumber);
        return ResBody.buildSuccessResBody(projectNumber);
    }

    /***
     * 当前用户是否有发起流程权限
     * @return
     */
    @RequestMapping(value = "/isHaveAuth")
    @ResponseBody
    //http://localhost:8081/Portal/CustomerComplaintsController/isHaveAuth?userId=e115c519-8395-4da2-b507-8a67ab3e0267
    public JSONObject isHaveAuth(String userId, String[] departments) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("state", "fail");
        try {
            User user = (User) getEngine().getOrganization().GetUnit(userId);

            //组织名称
            Unit departmentUnit = getEngine().getOrganization().GetUnit(user.getParentID());

            //从当前组织中查找
            for (String varStr : departments) {
                if (varStr.equals(departmentUnit.getName())) {
                    jsonObject.put("state", "success");
                    break;
                }
            }

            //不存在则从上级部门查找
            if (!"success".equals(jsonObject.getString("state"))) {

                if (null != user.getParentID() && !"".equals(user.getParentID())) {
                    Unit unitParent = getEngine().getOrganization().GetUnit(departmentUnit.getParentID());
                    for (String varStr : departments) {
                        if (varStr.equals(unitParent.getName())) {
                            jsonObject.put("state", "success");
                            break;
                        }
                    }
                }

            }

        } catch (Exception e) {
            jsonObject.put("state", "fail");
            jsonObject.put("erroStr", e.getMessage());
            e.printStackTrace();
        }


        return jsonObject;
    }

    /***
     * 发起退换货表单
     * @param instanceId
     * @return
     */
    @RequestMapping(value = "/createGoodsReturnForm")
    @ResponseBody
    public JSONObject createGoodsReturnForm(String instanceId) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("state", "success");

        try {
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            HashMap<String, Object> valueTables = instanceData.getBizObject().getValueTable();

            //数据映射
            String projectNumber = valueTables.get("Number02").toString();
            String complainDate = valueTables.get("ComplainDate02").toString();
            String customerStr = valueTables.get("Customer01").toString();
            String customerNo = valueTables.get("CustomerNo").toString();
            String shortCustomerName=valueTables.get("KsQcustomerShortName").toString();

            //牌号
            String productStr = valueTables.get("Product01").toString();
            //批号
            String lotNo = valueTables.get("LotNo").toString();
            //色号
            String colorNo = valueTables.get("Color01").toString();
            //投诉内容
            String complaninsContent = valueTables.get("ComplainsContent").toString();
            //研发员
            String rdPerson = valueTables.get("RD01").toString();
            //业务员
            String salePerson = valueTables.get("Sales08").toString();


            List<DataItemParam> dataItemParams = new ArrayList<>();
            dataItemParams.add(new DataItemParam("Number04", projectNumber));
            dataItemParams.add(new DataItemParam("ComDate05", complainDate));
            dataItemParams.add(new DataItemParam("Customer05", customerStr));
            dataItemParams.add(new DataItemParam("Customer06", customerNo));
            dataItemParams.add(new DataItemParam("Product04", productStr));
            dataItemParams.add(new DataItemParam("Lot05", lotNo));
            dataItemParams.add(new DataItemParam("Color04", colorNo));
            dataItemParams.add(new DataItemParam("ComContent05", complaninsContent));
            dataItemParams.add(new DataItemParam("RD05", rdPerson));
            dataItemParams.add(new DataItemParam("Sales05", salePerson));
            dataItemParams.add(new DataItemParam("KsQcustomerShortName", shortCustomerName));


            //发起人
            User user = (User) getEngine().getOrganization().GetUnit(instanceData.getInstanceContext().getOriginator());

            //发起流程
            BPMServiceResult bpmServiceResult = bpmService.StartWorkflow("H3", "Authine", "Return05", user.getCode(), false, dataItemParams);

            //等待1秒
            Thread.sleep(500);
            String workItemId = SqlUtil.doQuery(String.format("select objectid from OT_workitem where instanceId = '%s' and ActivityCode = 'Activity2' and Participant = '%s' limit 1", bpmServiceResult.getInstanceId(), user.getObjectID())).getRows().get(0).getString(0);

            /*String pc_url="http://www.kumhosunny.cn:8099/Portal/template/ddhome.html?loginfrom=dingtalk&WorkItemID="+workItemId+"&time="+System.currentTimeMillis();
            String mobile_url="http://www.kumhosunny.cn:8099/Mobile/#/dingtalkmsg/"+workItemId+"?time="+System.currentTimeMillis();
            //发送消息通知用户
            //子流程数据
            InstanceData sonData=new InstanceData(getEngine(),bpmServiceResult.getInstanceId(),User.AdministratorID);

            Notification notification=new Notification(OThinker.H3.Entity.Notification.NotifyType.DingTalk,null,user.getObjectID(),
                    user.getDingTalkAccount(),null,0,bpmServiceResult.getInstanceId(),
                    "团队OKR完成情况及绩效评价"+sonData.getInstanceContext().getInstanceName(),"您有一条流程待办,点击查看",null,mobile_url,pc_url,null);

            this.getEngine().getNotifier().Notify(notification);*/

            //访问地址 WorkItemSheets.html?WorkItemID=2bdf18f7-1e1f-4a92-8929-65a368a1d998
            String hrefAddress = "/WorkItemSheets.html?WorkItemID=" + workItemId;
            jsonObject.put("url", hrefAddress);
        } catch (Exception e) {
            jsonObject.put("state", "fail");
            jsonObject.put("erroStr", e.getMessage());
            e.printStackTrace();
        }

        return jsonObject;
    }

    /***
     * 发起补偿管理表单
     * @param instanceId
     * @return
     */
    //7ba27cbd-1bba-4f79-8f0b-dd8c3c82526e
    //http://www.kumhosunny.cn:8099/Portal/CustomerComplaintsController/createCompansateForm?instanceId=73c843e3-d794-497e-9d1e-43793dd4303d
    @RequestMapping(value = "/createCompansateForm")
    @ResponseBody
    public JSONObject createCompansateForm(String instanceId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("state", "success");
        try {
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            HashMap<String, Object> valueTables = instanceData.getBizObject().getValueTable();
            //数据映射
            String projectNumber = valueTables.get("Number02").toString();
            String complainDate = valueTables.get("ComplainDate02").toString();
            String customerStr = valueTables.get("Customer01").toString();
            String customerNo = valueTables.get("CustomerNo").toString();
            String shortCustomerName=valueTables.get("KsQcustomerShortName").toString();

            //牌号
            String productStr = valueTables.get("Product01").toString();
            //批号
            String lotNo = valueTables.get("LotNo").toString();
            //色号
            String colorNo = valueTables.get("Color01").toString();
            //投诉内容
            String complaninsContent = valueTables.get("ComplainsContent").toString();
            //研发员
            String rdPerson = valueTables.get("RD01").toString();
            //产品线
            String productLine = valueTables.get("ProductLine01").toString();
            //发生数量
            String consumedQuantity = valueTables.get("ConsumedQuantity02").toString();


            List<DataItemParam> dataItemParams = new ArrayList<>();
            dataItemParams.add(new DataItemParam("Number03", projectNumber));
            dataItemParams.add(new DataItemParam("ComplainDate03", complainDate));
            dataItemParams.add(new DataItemParam("Customer03", customerStr));
            dataItemParams.add(new DataItemParam("CustomerNo03", customerNo));
            dataItemParams.add(new DataItemParam("Product03", productStr));
            dataItemParams.add(new DataItemParam("LotNo03", lotNo));
            dataItemParams.add(new DataItemParam("Color03", colorNo));
            dataItemParams.add(new DataItemParam("ComplainContent", complaninsContent));
            dataItemParams.add(new DataItemParam("RD001", rdPerson));
            dataItemParams.add(new DataItemParam("Proline001", productLine));
            dataItemParams.add(new DataItemParam("Quantity03", consumedQuantity));
            dataItemParams.add(new DataItemParam("KsQcustomerShortName", shortCustomerName));

            //封装补偿审批人子表数据
            List<HashMap<String, Object>> reviewPersonList = new ArrayList<>();
            HashMap<String, Object> yyjlMap=new HashMap<>();
            yyjlMap.put("Post01", "营业经理");
            reviewPersonList.add(yyjlMap);
            HashMap<String, Object> yyfzMap=new HashMap<>();
            yyfzMap.put("Post01", "营业副总");
            reviewPersonList.add(yyfzMap);
            HashMap<String, Object> yfzjMap=new HashMap<>();
            yfzjMap.put("Post01", "研发总监");
            reviewPersonList.add(yfzjMap);
            HashMap<String, Object> zljlMap=new HashMap<>();
            zljlMap.put("Post01", "质量经理");
            reviewPersonList.add(zljlMap);
            HashMap<String, Object> zjlMap=new HashMap<>();
            zjlMap.put("Post01", "总经理");
            reviewPersonList.add(zjlMap);

            dataItemParams.add(new DataItemParam("Approve01", reviewPersonList));


            //发起人
            User user = (User) getEngine().getOrganization().GetUnit(instanceData.getInstanceContext().getOriginator());

            //发起流程
            BPMServiceResult bpmServiceResult = bpmService.StartWorkflow("H3", "Authine", "Compensate", user.getCode(), false, dataItemParams);

            //等待.5秒
            Thread.sleep(500);
            String workItemId = SqlUtil.doQuery(String.format("select objectid from OT_workitem where instanceId = '%s' and ActivityCode = 'Activity2' and Participant = '%s' limit 1", bpmServiceResult.getInstanceId(), user.getObjectID())).getRows().get(0).getString(0);

            //获取当前发起流程的数据
            InstanceData nowInstanceData = new InstanceData(getEngine(), bpmServiceResult.getInstanceId(), User.AdministratorID);
            BizObject[] bizObjects = (BizObject[]) nowInstanceData.getBizObject().getValueTable().get("Approve01");
            //所有节点参与者
            List<HashMap<String, Object>> allParticipant = new ArrayList<HashMap<String, Object>>();

            logger.warn("根据InstanceId查询所有节点参与者:" + bpmServiceResult.getInstanceId());

            InstanceContext instanceContext = nowInstanceData.getInstanceContext();
            Activity[] activities = nowInstanceData.getWorkflow().getActivities();

            if (null != instanceContext) {

                PublishedWorkflowTemplate workflowTemplate = getEngine().getWorkflowManager().GetPublishedTemplate(instanceContext.getWorkflowCode(), instanceContext.getWorkflowVersion());

                if (activities.length != 0) {

                    for (Activity activity : activities) {

                        if (!"".equals(activity.getDisplayName())) {
                            HashMap<String, Object> resultMaps = new HashMap<>();
                            //ActivityCode
                            Object tempVar = workflowTemplate.GetActivityByCode(activity.getActivityCode());
                            ClientActivityBase activityBase = (ClientActivityBase) ((tempVar instanceof ClientActivityBase) ? tempVar : null);

                            if (null != activityBase) {
                                String[] participantIds = activityBase.ParseParticipants(nowInstanceData, getEngine().getOrganization());
                                List<String> participantList = new ArrayList<>(Arrays.asList(participantIds));

                                if (participantList.size() > 0) {
                                    //ActivityDisplayName
                                    resultMaps.put("displayName", activity.getDisplayName());
                                    resultMaps.put("activityCode", activity.getActivityCode());
                                    //nowParticipant
                                    resultMaps.put("participants", participantList);
                                    allParticipant.add(resultMaps);
                                }

                            }

                        }

                    }
                }

            }
            logger.warn("参与者数据整理完成:" + bpmServiceResult.getInstanceId());
            //动态录入对应审批人
            for (BizObject bizObject : bizObjects) {

                String roleStr = bizObject.getValueTable().get("Post01").toString();

                for (int i = 0; i < allParticipant.size(); i++) {
                    String displayName = allParticipant.get(i).get("displayName").toString();

                    if (displayName.indexOf(roleStr) != -1) {
                        //参与人
                        List<String> participants = (List<String>) allParticipant.get(i).get("participants");
                        bizObject.setItem("Name001", participants.get(0));
                    }

                }

            }
            nowInstanceData.Submit();
            //访问地址 WorkItemSheets.html?WorkItemID=2bdf18f7-1e1f-4a92-8929-65a368a1d998
            String hrefAddress = "/WorkItemSheets.html?WorkItemID=" + workItemId;
            jsonObject.put("url", hrefAddress);
        } catch (Exception e) {
            jsonObject.put("state", "fail");
            jsonObject.put("erroStr", e);
            e.printStackTrace();
        }

        return jsonObject;
    }

    /***
     * 发起紧急生产单
     * @param instanceId
     * @return
     */
    @RequestMapping(value = "/createUrgentForm")
    @ResponseBody
    public JSONObject createUrgentForm(String instanceId) {
        JSONObject jsonObject = new JSONObject();

        try {
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            HashMap<String, Object> valueTables = instanceData.getBizObject().getValueTable();

            //数据映射
            String projectNumber = valueTables.get("Number02").toString();
            String complainDate = valueTables.get("ComplainDate02").toString();
            String customerStr = valueTables.get("Customer01").toString();
            String customerNo = valueTables.get("CustomerNo").toString();
            String shortCustomerName=valueTables.get("KsQcustomerShortName").toString();


            //牌号
            String productStr = valueTables.get("Product01").toString();
            //批号
            String lotNo = valueTables.get("LotNo").toString();
            //色号
            String colorNo = valueTables.get("Color01").toString();
            //投诉内容
            String complaninsContent = valueTables.get("ComplainsContent").toString();
            //研发员
            String rdPerson = valueTables.get("RD01").toString();
            //业务员
            String salePerson = valueTables.get("Sales08").toString();


            List<DataItemParam> dataItemParams = new ArrayList<>();
            dataItemParams.add(new DataItemParam("Number01", projectNumber));
            dataItemParams.add(new DataItemParam("ComplainDate01", complainDate));
            dataItemParams.add(new DataItemParam("Customer01", customerStr));
            dataItemParams.add(new DataItemParam("CustomerNo", customerNo));
            dataItemParams.add(new DataItemParam("Product01", productStr));
            dataItemParams.add(new DataItemParam("Lot01", lotNo));
            dataItemParams.add(new DataItemParam("Color01", colorNo));
            dataItemParams.add(new DataItemParam("ComplainContent01", complaninsContent));
            dataItemParams.add(new DataItemParam("RD01", rdPerson));
            dataItemParams.add(new DataItemParam("Sales01", salePerson));
            dataItemParams.add(new DataItemParam("KsQcustomerShortName", shortCustomerName));


            //发起人
            User user = (User) getEngine().getOrganization().GetUnit(instanceData.getInstanceContext().getOriginator());

            //发起流程
            BPMServiceResult bpmServiceResult = bpmService.StartWorkflow("H3", "Authine", "ReturnManagement", user.getCode(), false, dataItemParams);

            //等待1秒
            Thread.sleep(500);
            String workItemId = SqlUtil.doQuery(String.format("select objectid from OT_workitem where instanceId = '%s' and ActivityCode = 'Activity2' and Participant = '%s' limit 1", bpmServiceResult.getInstanceId(), user.getObjectID())).getRows().get(0).getString(0);

            /*String pc_url="http://www.kumhosunny.cn:8099/Portal/template/ddhome.html?loginfrom=dingtalk&WorkItemID="+workItemId+"&time="+System.currentTimeMillis();
            String mobile_url="http://www.kumhosunny.cn:8099/Mobile/#/dingtalkmsg/"+workItemId+"?time="+System.currentTimeMillis();
            //发送消息通知用户
            //子流程数据
            InstanceData sonData=new InstanceData(getEngine(),bpmServiceResult.getInstanceId(),User.AdministratorID);

            Notification notification=new Notification(OThinker.H3.Entity.Notification.NotifyType.DingTalk,null,user.getObjectID(),
                    user.getDingTalkAccount(),null,0,bpmServiceResult.getInstanceId(),
                    "团队OKR完成情况及绩效评价"+sonData.getInstanceContext().getInstanceName(),"您有一条流程待办,点击查看",null,mobile_url,pc_url,null);

            this.getEngine().getNotifier().Notify(notification);*/

            //访问地址 WorkItemSheets.html?WorkItemID=2bdf18f7-1e1f-4a92-8929-65a368a1d998
            String hrefAddress = "/WorkItemSheets.html?WorkItemID=" + workItemId;
            jsonObject.put("state", "success");
            jsonObject.put("url", hrefAddress);


        } catch (Exception e) {
            jsonObject.put("state", "fail");
            jsonObject.put("erroStr", e.getMessage());
            e.printStackTrace();
        }


        return jsonObject;

    }


    /***
     * 补偿表单数据返还
     * @param instanceId
     * @return
     */
    //http://localhost:8081/Portal/CustomerComplaintsController/compansateFormBackData?instanceId=73c843e3-d794-497e-9d1e-43793dd4303d
    @RequestMapping(value = "/compansateFormBackData")
    @ResponseBody
    public JSONObject compansateFormBackData(String instanceId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("state", "success");

        try {
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            HashMap<String, Object> valueTables = instanceData.getBizObject().getValueTable();

            //项目编号
            String projectNumber = valueTables.get("Number03").toString();

            //补偿方式
            String compenType = valueTables.get("Compen001").toString();

            //补偿数量
            String compenTon = valueTables.get("CQuantity").toString();

            //补偿金额
            String compenMoney = valueTables.get("Cost001").toString();

            //客诉单数据
            InstanceData compenInstanceData = new InstanceData(getEngine(), this.findComplaintsForm(projectNumber), User.AdministratorID);
            String compenObjectId = compenInstanceData.getBizObject().getObjectID();
            String insertSqlStr = String.format("INSERT INTO i_Compensate01 VALUES('%s','%s','%s','%s',0,'%s','Compensate01','%s')"
                    , UUID.randomUUID(), compenMoney, compenType, DateTimeUtil.format(new Date()), compenTon, compenObjectId);

            //录入数据库
            Integer resultNumber = SqlUtil.executeInsert(insertSqlStr);
            jsonObject.put("result", resultNumber);


        } catch (Exception e) {
            jsonObject.put("state", "fail");
            e.printStackTrace();
        }


        return jsonObject;
    }

    /***
     * 退货流程数据返回
     * @param instanceId
     * @return
     */
    //http://www.kumhosunny.cn:8099/Portal/CustomerComplaintsController/goodsReturnBackData?instanceId=3c1354c4-4634-4382-a55b-74492594acc3
    @RequestMapping(value = "/goodsReturnBackData")
    @ResponseBody
    public JSONObject goodsReturnBackData(String instanceId) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("state", "success");

        InstanceData instanceData = null;
        try {
            instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            HashMap<String, Object> valueTables = instanceData.getBizObject().getValueTable();

            //项目编号
            String projectNumber = valueTables.get("Number04").toString();
            //获取客诉单流程id
            String customerComplaintsInstanceId = this.findComplaintsForm(projectNumber);

            //获取子表数据
            BizObject[] bizObjects = (BizObject[]) valueTables.get("ActualRe01");
            //总吨数
            double totalTon = 0.0;
            //退货时间
            Date backGoodsTime = null;
            if (null != bizObjects && bizObjects.length != 0) {
                backGoodsTime = (Date) bizObjects[0].getValueTable().get("Date055");
                for (BizObject bizObject : bizObjects) {
                    totalTon += Double.parseDouble(bizObject.getValueTable().get("Quantity055").toString());
                }
            }

            //客诉单数据
            InstanceData customerInstanceData = new InstanceData(getEngine(), customerComplaintsInstanceId, User.AdministratorID);
            HashMap<String, Object> customerValueTables = customerInstanceData.getBizObject().getValueTable();
            String customerObjectId = customerInstanceData.getBizObject().getObjectID();
            String insertSqlStr = String.format("INSERT INTO i_Return01 VALUES('%s',null,'%s',%s,0,'Return01','%s',0)"
                    , UUID.randomUUID(), DateTimeUtil.format(backGoodsTime), totalTon, customerObjectId);

            //录入数据库
            Integer resultNumber = SqlUtil.executeInsert(insertSqlStr);
            jsonObject.put("result", resultNumber);
        } catch (Exception e) {
            jsonObject.put("state", "fail");
            e.printStackTrace();
        }

        return jsonObject;

    }

    /***
     * 返回流程正常运行地址
     * @param ObjectId
     * @param response
     */
    //http://localhost:8081/Portal/CustomerComplaintsController/findHref?ObjectId=8c7f4086-87e3-4ff9-b71d-2d1bfb6fd851
    @RequestMapping(value = "/findHref")
    public void returnProjectRunAddress(String ObjectId, HttpServletResponse response){
        StringBuffer sb=new StringBuffer();
        sb.append("SELECT otw.ObjectID AS 'runid',otf.ObjectID AS 'endid' FROM i_containmentactions ic");
        sb.append(" LEFT JOIN ot_instancecontext oti ON (ic.ObjectID=oti.BizObjectId)");
        sb.append( "LEFT JOIN ot_workitem otw ON (oti.ObjectID=otw.InstanceId)");
        sb.append( "LEFT JOIN ot_workitemfinished otf ON (oti.ObjectID=otf.InstanceId)");
        sb.append(" WHERE ic.ObjectId='"+ObjectId+"' GROUP BY ic.ObjectID");
        response.setContentType("text/html;charset=UTF-8");
        String address="http://www.kumhosunny.cn:8099/Portal/WorkItemSheets.html?WorkItemID=";
        try {
            DataTable dataTable=SqlUtil.doQuery(sb.toString());

            if(dataTable.getRows().size()>0){
                PrintWriter printWriter=response.getWriter();
                String runInstanceId= dataTable.getRows().get(0).getString("runid");

                if(null==runInstanceId || "".equals(runInstanceId)){
                    String workItemId=dataTable.getRows().get(0).getString("endid");
                    //backAddress
                    if(!"".equals(workItemId)){
                        printWriter.print("<script>location.href='"+address+workItemId+"'</script>");
                        printWriter.close();
                    }else{
                        printWriter.print("<script>alert('这个流程可能已经结束')</script>");
                        printWriter.close();
                    }

                }else{
                    //backAddress
                    printWriter.print("<script>location.href='"+address+runInstanceId+"'</script>");
                    printWriter.close();
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /***
     * 数据测试
     */
    //http://localhost:8081/Portal/CustomerComplaintsController/contextTest
    @RequestMapping(value = "/contextTest")
    @ResponseBody
    public String contextTest() {
        String instanceId = "ce91e020-bf79-48c5-881b-4e681ba89930";
        String activityCode="Activity3";
        String result = "";

        try {
            List<Object> test=getParticipants(activityCode,instanceId);
            System.out.printf(test.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*try {
            //所有节点参与者
            List<HashMap<String, Object>> allParticipant = new ArrayList<HashMap<String, Object>>();

            List<HashMap<String, Object>> resultData = new ArrayList<HashMap<String, Object>>();
            logger.warn("根据InstanceId查询所有节点参与者:" + instanceId);

            InstanceData instanceDataPerson = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            InstanceContext instanceContext = getEngine().getInstanceManager().GetInstanceContext(instanceId);

            Activity[] activities = instanceDataPerson.getWorkflow().getActivities();

            if (null != instanceContext) {

                PublishedWorkflowTemplate workflowTemplate = getEngine().getWorkflowManager().GetPublishedTemplate(instanceContext.getWorkflowCode(), instanceContext.getWorkflowVersion());

                if (activities.length != 0) {

                    for (Activity activity : activities) {

                        if (!activity.getActivityCode().equals("Activity1") && !activity.getActivityCode().equals("Activity4")) {
                            HashMap<String, Object> resultMaps = new HashMap<String, Object>();
                            Object tempVar = workflowTemplate.GetActivityByCode(activity.getActivityCode());
                            ClientActivityBase activityBase = (ClientActivityBase) ((tempVar instanceof ClientActivityBase) ? tempVar : null);

                            if (null != activityBase) {
                                String[] participantIds = activityBase.ParseParticipants(instanceDataPerson, getEngine().getOrganization());
                                List<String> participantList = new ArrayList<>(Arrays.asList(participantIds));

                                if (participantList.size() > 0) {
                                    //ActivityDisplayName
                                    resultMaps.put("displayName", activity.getDisplayName());
                                    resultMaps.put("activityCode", activity.getActivityCode());
                                    //nowParticipant
                                    resultMaps.put("participants", participantList);
                                    allParticipant.add(resultMaps);
                                }

                            }

                        }

                    }
                }

            }

            return allParticipant.toString();

        } catch (Exception e) {
            result = e.getMessage();
            e.printStackTrace();
        }*/

        return result;
    }

    /***
     * 获取流程节点
     * @param activityCode
     * @param instanceId
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws Exception
     */
    public final List<Object> getParticipants(String activityCode, String instanceId)
            throws InstantiationException, IllegalAccessException, Exception {
        // 流程
        // 流程模板
        // 活动信息
        net.sf.json.JSONObject json = ExecuteFunctionRun(null);
        if (json != null) {
            return null;
        }

        if (!DotNetToJavaStringHelper.isNullOrEmpty(activityCode)
                && !DotNetToJavaStringHelper.isNullOrEmpty(instanceId)) {
            InstanceContext instanceContext = getEngine().getInstanceManager().GetInstanceContext(instanceId);
            if (instanceContext != null) {
                PublishedWorkflowTemplate template = getEngine().getWorkflowManager()
                        .GetPublishedTemplate(instanceContext.getWorkflowCode(), instanceContext.getWorkflowVersion());
                if (template != null) {
                    Object tempVar = template.GetActivityByCode(activityCode);
                    ClientActivityBase activity =
                            (ClientActivityBase)((tempVar instanceof ClientActivityBase) ? tempVar : null);
                    InstanceData instanceData = new InstanceData(getEngine(), instanceId, null);
                    String[] participantIds = activity.ParseParticipants(instanceData, getEngine().getOrganization());
                    List<String> particIds = new ArrayList<String>();
                    for (int i = 0; i < participantIds.length; i++) {
                        particIds.add(participantIds[i]);
                    }
                    List<Unit> participantUsers = getEngine().getOrganization().GetUnits(particIds);
                    if (participantUsers != null) {
                        List<Object> participantUserNames = new ArrayList<Object>();
                        for (Unit u : participantUsers) {
                            if (u != null && u.getUnitType() == UnitType.User) {
                                // update by zhangj
                                User user = (User)u;
                                Map<String, Object> item = new HashMap<String, Object>();
                                item.put("Name", user.getName());
                                item.put("Code", user.getCode());
                                item.put("ObjectID", user.getObjectID());
                                participantUserNames.add(item);
                            }
                        }
                        return participantUserNames;
                    }
                }
            }
        }
        return null;
    }


}
